package com.chezhujie.www.controller;



import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.chezhujie.www.core.page.Pagination;
import com.chezhujie.www.domain.Czjawardoff;
import com.chezhujie.www.service.CzjawardoffService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;





@Controller
@RequestMapping("awardoff")
public class CzjawardoffController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(CzjawardoffController.class);
	public CzjawardoffController() {
	}
 
 
 	/**
	 * czj_awardoff 奖品线上新增页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardoffAdd.do")
	public String add(HttpServletRequest request, ModelMap model) {
		model.addAttribute("czjawardoff", new Czjawardoff());
      setDict(model);
		return "awardoff/czjawardoffEdit";
	}

	/**
	 * czj_awardoff 奖品线上保存
	 * 
	 * @param czjawardoff
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardoffSave.do")
	public String save(Czjawardoff czjawardoff, 
			@RequestParam(value = "first", required = false)  MultipartFile first,
			HttpServletRequest request, ModelMap model) throws Exception{
      
		try {
			//路径
			String pathRoot = request.getSession().getServletContext()
					.getRealPath("");
			String path = "";				
			// 第一张头像
			if (!first.isEmpty() && first.getSize()>0) {
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				path = "/uploadvoteorder/" + uuid + "." + "jpg";
				File file = new File(pathRoot + "/uploadvoteorder");
				if (!file.exists()) {
					file.mkdir();
				}
				first.transferTo(new File(pathRoot + path));					
				//更新才删
				String jpgPic = czjawardoff.getThingPath();					
				if(jpgPic != null && jpgPic.length()>5){
					jpgPic = jpgPic.substring(1, jpgPic.length());
				}
				deleteFile(pathRoot + jpgPic);
				//更新才设置图片路径				
				czjawardoff.setThingPath(path);
			}			
			
			if(czjawardoff.getAwardoffId()!=null&&!czjawardoff.getAwardoffId().equals("")){
				// 编辑
				czjawardoffService.updateCzjawardoff(czjawardoff);
				model.addAttribute("message",2);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "编辑czj_awardoff 奖品线上", "awardoffId="+czjawardoff.getawardoffId()));
			} else {
				// 新增
				czjawardoff.setCreatetime(new Date());
				czjawardoffService.insertCzjawardoff(czjawardoff);
				model.addAttribute("message",2);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "新增czj_awardoff 奖品线上", "awardoffId="+czjawardoff.getawardoffId()));
			}
   		} catch (Exception e) {
   			log.error("czjawardoff save error:", e); 
            throw e;
   		}
      
		return "redirect:czjawardoffEdit.do?awardoffId="+czjawardoff.getAwardoffId();
	}

	/**
	 * czj_awardoff 奖品线上删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("czjawardoffDelete.do")
	public String delete(@RequestParam("ids") List<String> awardoffIdList) throws Exception{
		try {
         if (awardoffIdList != null) {
   			czjawardoffService.deleteCzjawardoff(awardoffIdList);
   		}
         } catch (Exception e) {
   			log.error("czjawardoff delete error:", e); 
            throw e;
   		}
		return "redirect:czjawardoffList.do";
	}
	 
	/**
	 * czj_awardoff 奖品线上编辑页面
	 * 
	 * @param awardoffId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardoffEdit.do")
	public String edit(String awardoffId, HttpServletRequest request, ModelMap model) throws Exception{
      try {
          String message = request.getParameter("message");                  
          request.setAttribute("message", message);
   		Map<String, Object> param = new HashMap<String, Object>();
   		param.put("awardoffId", awardoffId);
         Czjawardoff czjawardoff = czjawardoffService.getCzjawardoff(param);
   		model.addAttribute("czjawardoff", czjawardoff);
         model.addAttribute("actionEdit", request.getParameter("actionEdit"));
         setDict(model);
         } catch (Exception e) {
   			log.error("czjawardoff edit error:", e); 
            throw e;
   		}
		return "awardoff/czjawardoffEdit";
	}

	/**
	 * czj_awardoff 奖品线上详情
	 * 
	 * @param awardoffId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardoffDetail.do")
	public String detail(String awardoffId, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{
      try {
      		Map<String, Object> param = new HashMap<String, Object>();
      		param.put("awardoffId", awardoffId);
            Czjawardoff czjawardoff = czjawardoffService.getCzjawardoff(param);
      		model.addAttribute("czjawardoff", czjawardoff);
            setDict(model);
            } catch (Exception e) {
   			log.error("czjawardoff detail error:", e); 
            throw e;
   		  }
		return "awardoff/czjawardoffView";
	}
	 
	/**
	 * czj_awardoff 奖品线上查询（分页）
	 * 
	 * @param czjawardoff
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardoffList.do")
	public String listPage(Czjawardoff czjawardoff, Integer pageNo, String order,
			String sort,HttpServletRequest request, ModelMap model) throws Exception{
      try {   
   		if (pageNo == null)
   			pageNo = 1;
         Pagination pagination = czjawardoffService.getCzjawardoffList(toMap(czjawardoff), 20, pageNo,
   				order, sort);          
   		model.addAttribute("pagination", pagination);
         setDict(model);
         } catch (Exception e) {
			log.error("czjawardoff listPage error:", e); 
         throw e;
		   }
		return "awardoff/czjawardoffList";
	}
	 
	/**
	 * czj_awardoff 奖品线上查询
	 * 
	 * @param czjawardoff
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjawardoffList1.do")
	public String list(Czjawardoff czjawardoff, HttpServletRequest request, ModelMap model) throws Exception{
      try {
   		Map<String,Object> map = czjawardoffService.getCzjawardoffList(toMap(czjawardoff));
   		model.addAttribute("list", map.get("rows"));
   		model.addAttribute("total", map.get("total"));
         setDict(model);
         } catch (Exception e) {
   			log.error("czjawardoff list error:", e); 
            throw e;
   		}
		return "awardoff/czjawardoffList";
	}
	
	/**
	 * czj_awardoff  图片广告详情
	 * 
	 * @param awardoffId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("queryImgOrder.do")
	public void detail1111(String ext1, String awardoffId, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{
      try {
      		Map<String, Object> param = new HashMap<String, Object>();
      		param.put("ext1", ext1);     		    		    		
            Czjawardoff czjawardoff = czjawardoffService.queryImgOrder(param);
                          
            //插入时
      		if("".equals(awardoffId)){  
      			     if(czjawardoff !=null){
      			    	jsonResult(1,"","重复的顺序",0,response);  
      			     }else{
      			    	jsonResult(1,"","可以添加",1,response);  
      			     }      				      			         
	      		}
      		//更新时      		
      		if(!"".equals(awardoffId)){
          		//查询自己
          		Map<String, Object> paramMy = new HashMap<String, Object>();
          		paramMy.put("awardoffId", awardoffId);
                Czjawardoff myorder = czjawardoffService.getCzjawardoff(paramMy);
                String myordernum = myorder.getExt1();
                //和自己相同的可以更新
                if(myordernum.equals(ext1)){
                	jsonResult(1,"","可以添加",1,response); 
                }else{
                  //如果跟自己的不相同
                	List<String> listString = czjawardoffService.getCzjawardoffListStringALL();
                	boolean flag = true;
                	//循环数据库字段,如果相同,就代表有重复
                	for(String str : listString){
                		if(ext1.equals(str)){
                			flag= false;
                		}
                	}
                	if(!flag){
                		jsonResult(1,"","重复的顺序",0,response); 
                	}else{
                		jsonResult(1,"","可以添加",1,response); 
                	}
                	
                	
                }
                                                
      		}        		
     		    		      		
            } catch (Exception e) {
            jsonResult(1,"","系统异常","",response);
   			log.error("czjawardoff detail error:", e); 
            throw e;
   		  }
		
	}	
	
	 

 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param czjawardoff
	 * @return
	 */	private Map<String,Object> toMap(Czjawardoff czjawardoff){
		Map<String,Object> map=new HashMap<String, Object>();
      		if(czjawardoff.getAwardoffId()!=null&&!czjawardoff.getAwardoffId().equals("")){
			map.put("awardoffId", czjawardoff.getAwardoffId());
		}
		if(czjawardoff.getProbability()!=null&&!czjawardoff.getProbability().equals("")){
			map.put("probability", czjawardoff.getProbability());
		}
		if(czjawardoff.getCount()!=null&&!czjawardoff.getCount().equals("")){
			map.put("count", czjawardoff.getCount());
		}
		if(czjawardoff.getThingId()!=null&&!czjawardoff.getThingId().equals("")){
			map.put("thingId", czjawardoff.getThingId());
		}
		if(czjawardoff.getThingName()!=null&&!czjawardoff.getThingName().equals("")){
			map.put("thingName", czjawardoff.getThingName());
		}
		if(czjawardoff.getShopId()!=null&&!czjawardoff.getShopId().equals("")){
			map.put("shopId", czjawardoff.getShopId());
		}
		if(czjawardoff.getThingPath()!=null&&!czjawardoff.getThingPath().equals("")){
			map.put("thingPath", czjawardoff.getThingPath());
		}
		if(czjawardoff.getCreatetime()!=null&&!czjawardoff.getCreatetime().equals("")){
			map.put("createtime", czjawardoff.getCreatetime());
		}
		if(czjawardoff.getExt1()!=null&&!czjawardoff.getExt1().equals("")){
			map.put("ext1", czjawardoff.getExt1());
		}
		if(czjawardoff.getExt2()!=null&&!czjawardoff.getExt2().equals("")){
			map.put("ext2", czjawardoff.getExt2());
		}
		if(czjawardoff.getExt3()!=null&&!czjawardoff.getExt3().equals("")){
			map.put("ext3", czjawardoff.getExt3());
		}      
		return map;
	}
   
	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
	private void setDict(ModelMap model){
		
	}

	//删除更新的图片
	 public void deleteFile(String jgpName){	 
		 File f = new File(jgpName); // 输入要删除的文件位置
		 if(f.exists()){
			 f.delete();
		 }
		
	 }	


   
      
	@Resource
	private CzjawardoffService czjawardoffService;


}